//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/login/sms_code_type.dart';
import 'package:hktk_app/model/login/change_model.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/login/phone_input_widget.dart';

/// 重置密码组件
class ResetPasswordWidget extends StatefulWidget {
  /// 手机号码
  final String phoneStr;

  /// 标题名称
  final String title;

  /// 是否是重置密码，false位忘记密码
  final bool resetPass;

  const ResetPasswordWidget({
    super.key,
    required this.phoneStr,
    required this.title,
    required this.resetPass,
  });

  @override
  State<ResetPasswordWidget> createState() => _ResetPasswordWidgetState();
}

class _ResetPasswordWidgetState extends State<ResetPasswordWidget> {
  late BuildContext _context;

  /// 手机号输入框控制器
  late TextEditingController _phoneController;

  /// 密码输入框控制器
  late TextEditingController _passwordController;

  /// 验证码输入框控制器
  late TextEditingController _captchaController;

  /// 验证手机号是否正确的方法
  final RegExp exp = RegExp(
      '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$');

  @override
  void initState() {
    super.initState();
    _phoneController = TextEditingController();
    _passwordController = TextEditingController();
    _captchaController = TextEditingController();

    if (widget.phoneStr != "") {
      _phoneController.text = widget.phoneStr;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    _captchaController.dispose();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return MediaQuery.removePadding(
      removeTop: true,
      context: _context,
      child: ListView(
        children: [
          hiSpace(height: 164),
          Column(
            children: [
              _modeItem(),
              hiSpace(height: 56),
              _inputItem(),
              hiSpace(height: 80),
              _btnItem(),
            ],
          ),
        ],
      ),
    );
  }

  /// 标题
  _modeItem() {
    return Padding(
      padding: EdgeInsets.only(left: 40),
      child: Row(
        children: [
          Text(
            widget.title,
            style: FontUtil.fontBlack1(
              30,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// 输入框
  _inputItem() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 54),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          PhoneInputWidget.phone(
            controller: _phoneController,
          ),
          hiSpace(height: 40),
          PhoneInputWidget.captcha(
            controller: _captchaController,
            rightOnTapFun: _sendCaptcha,
          ),
          hiSpace(height: 40),
          PhoneInputWidget.password(
            controller: _passwordController,
            tips: "请输入不少于8位的密码",
          ),
        ],
      ),
    );
  }

  /// 按钮组件
  _btnItem() {
    return GestureDetector(
      onTap: _onTapFunQd,
      child: Container(
        width: 400,
        margin: EdgeInsets.symmetric(horizontal: 48),

        padding: EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: colorBlue1,
          borderRadius: BorderRadius.all(Radius.circular(44)),
        ),
        child: Center(child: Text(
          "确定",
          style: FontUtil.fontWhile1(24, fontWeight: FontWeight.w500),
        )),
      ),
    );
  }

  /// 发送验证码方法
  Future<bool> _sendCaptcha() async {
    // 获取输入手机号
    String text = _phoneController.text;
    if (!exp.hasMatch(text)) {
      ToastUtil.show(context: _context, msg: "请输入正确的手机号");
      return false;
    }
    // 发送验证码方法
    bool res;
    try {
      await LoginDao.phoneCode(
        phone: text,
        smsCodeType:
        widget.resetPass ? SmsCodeType.resetPass : SmsCodeType.forgetPass,
      );
      res = true;
    } catch (e) {
      res = false;
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        ToastUtil.show(context: _context, msg: msg);
      });
    }
    return res;
  }

  /// 确定点击方法
  _onTapFunQd() async {
    String phone = _phoneController.text;
    String captcha = _captchaController.text;
    String password = _passwordController.text;
    // 验证条件
    if (!exp.hasMatch(phone)) {
      ToastUtil.show(context: _context, msg: "请输入正确的手机号");
      return;
    }
    if (captcha == "") {
      ToastUtil.show(context: _context, msg: "请输入验证码");
      return;
    }
    if (password == "") {
      ToastUtil.show(context: _context, msg: "请输入密码");
      return;
    } else {
      if (password.length < 8) {
        ToastUtil.show(context: _context, msg: "请输入不少于8位的密码");
        return;
      }
    }
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 发送请求，等待完成
    LoginDao.changePass(
      userAccount: phone,
      code: captcha,
      credential: password,
      change: widget.resetPass,
    ).then((ChangeModel changeModel) {
      ToastUtil.loadingBoxRemove();
      // 提示
      ToastUtil.show(context: _context, msg: "成功修改");

      Navigator.pop(_context);
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }
}
